package library.and.xps.com.step.view.activity;

import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jude.utils.JUtils;
import com.orhanobut.logger.Logger;
import com.squareup.okhttp.Request;
import com.zhy.autolayout.AutoLinearLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;

import cn.jpush.android.api.JPushInterface;
import library.and.xps.com.step.EventBusCommond;
import library.and.xps.com.step.R;
import library.and.xps.com.step.URLConstants;
import library.and.xps.com.step.m.model.RequestParams;
import library.and.xps.com.step.m.model.UpdateUserInfo;
import library.and.xps.com.step.m.netapi.OkHttpClientUtils;
import library.and.xps.com.step.net.ResponceWrapper;
import library.and.xps.com.step.util.CommonUtils;
import library.and.xps.com.step.util.HttpResponsHelper;
import library.and.xps.com.step.util.RequestCallback;
import library.and.xps.com.step.util.StepManager;
import library.and.xps.com.step.util.TeamHelper;
import library.and.xps.com.step.util.UserHelper;
import library.and.xps.com.step.view.base.BaseActivity;
import library.and.xps.com.step.view.fragment.ActCircleFragment;
import library.and.xps.com.step.view.fragment.PersonFragment;
import library.and.xps.com.step.view.fragment.RankingFragment;

public class NewMainActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener {
    ActCircleFragment fragmentActivityCircle;
    PersonFragment fragmentPerson;
    RankingFragment fragmentRanking;
    ArrayList<Fragment> data;
    ImageView iv_ranking, iv_act_circle, iv_person;
    TextView tv_ranking, tv_act_circle, tv_person;
    AutoLinearLayout al_ranking, al_act_circle, al_person;
    FragmentTransaction ft;
    FragmentManager fragmentManager;
    NavigationView navigationView;
    View slideHeaderView;
    private static final String UPDATE_USERINFO = "UPDATE_USERINFO";
    private static final String CHANGE_TODAY_FINISH_GOAL = "CHANGE_TODAY_FINISH_GOAL";

    @Override
    protected int getLayout() {
        return R.layout.activity_newmain;
    }

    @Override
    protected void setData() {

    }

    @Override
    protected void init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        data = new ArrayList<>();

        iv_ranking = r2v(R.id.iv_ranking);
        iv_act_circle = r2v(R.id.iv_act_circle);
        iv_person = r2v(R.id.iv_person);

        tv_ranking = r2v(R.id.tv_ranking);
        tv_act_circle = r2v(R.id.tv_act_circle);
        tv_person = r2v(R.id.tv_person);

        al_ranking = r2v(R.id.al_ranking);
        al_ranking.setOnClickListener(this);
        al_act_circle = r2v(R.id.al_act_circle);
        al_act_circle.setOnClickListener(this);
        al_person = r2v(R.id.al_person);
        al_person.setOnClickListener(this);

        navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        slideHeaderView = navigationView.inflateHeaderView(R.layout.nav_header_main);
        initTabs();

        fragmentPerson = new PersonFragment();
        fragmentActivityCircle = new ActCircleFragment();
        fragmentRanking = new RankingFragment();

        fragmentManager = getSupportFragmentManager();
        ft = fragmentManager.beginTransaction();
        ft.add(R.id.container, fragmentActivityCircle, fragmentActivityCircle.getClass().getName());
        ft.add(R.id.container, fragmentRanking, fragmentRanking.getClass().getName());
        ft.add(R.id.container, fragmentPerson, fragmentPerson.getClass().getName());
        hideAllFrag();
        ft.show(fragmentActivityCircle).commit();

        iv_act_circle.setImageResource(R.mipmap.tab_ball_w);
        al_act_circle.setBackgroundColor(Color.parseColor("#06D5A6"));
        tv_act_circle.setTextColor(Color.parseColor("#ffffff"));

        if (getUser() != null) {
            uploadJpushId();

            if (TeamHelper.getIns().hasTeam())
                uploadStep();

        }
    }

    private void initSlideHeader() {
        ImageView iv_header = (ImageView) slideHeaderView.findViewById(R.id.iv_user_head);
        TextView tv_username = (TextView) slideHeaderView.findViewById(R.id.tv_username);
        TextView tv_userteam = (TextView) slideHeaderView.findViewById(R.id.tv_userteam);
        iv_header.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(NewMainActivity.this, CustomPersonInfoActivity.class));
            }
        });
        tv_userteam.setText(TeamHelper.getIns().getCurT().getTname());
        tv_username.setText(getUser().getNickname());
        CommonUtils.setupCircleImg(this, iv_header, getUser().getIco());
    }

    /**
     * 上传JpushId
     */
    void uploadJpushId() {
        final String jpushid = JPushInterface.getRegistrationID(this);
        JSONObject json = RequestParams.getNewInstance().setUserid(getUser().getUserid()).setJpushid(jpushid).getJson();
        OkHttpClientUtils.postJsonStringAsync(this, URLConstants.USER.UpdateUserInfo, json.toString(), new RequestCallback() {
            @Override
            public void onFailure(Request request, Exception e) {
                if (e instanceof RuntimeException) {
                    JUtils.Toast(e.getMessage());
                }
            }

            @Override
            public void onResponse(ResponceWrapper response) {
                UpdateUserInfo updateUserInfo = new Gson().fromJson(response.getBody(), UpdateUserInfo.class);
                if (!HttpResponsHelper.SuccessResponce(updateUserInfo)) {
                    JUtils.Toast("修改失败");
                } else {
                    UserHelper.getInstance().updateUser("jpushid", jpushid);
                }
            }

            @Override
            public void onStart() {

            }
        }, UPDATE_USERINFO);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (getUser() == null) return;
        initSlideHeader();
    }

    /**
     * 上传今日步数
     */
    void uploadStep() {
        int currentStep = StepManager.getInstance().getStepToday();
        if (currentStep == -1) currentStep = 0;

        String data = URLConstants.USER.ChangeTodayFinishGoal + "?userid=" + getUser().getUserid() + "&finishgoal=" + currentStep + "&teamid=" + TeamHelper.getIns().getTid();
        OkHttpClientUtils.getDataAsync(this, data, new RequestCallback() {
            @Override
            public void onFailure(Request request, Exception e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(ResponceWrapper response) {
                if (HttpResponsHelper.SuccessResponce(response)) {
                    Logger.d(response.getBody());
                }
            }

            @Override
            public void onStart() {

            }
        }, CHANGE_TODAY_FINISH_GOAL);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceiveEvent(String param) {
        if (param.equals(EventBusCommond.OPEN_DRAWERMENU)) {
            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.openDrawer(GravityCompat.START);
        }
    }

    public void hideAllFrag() {
        fragmentPerson.hide();
        fragmentRanking.hide();
        fragmentActivityCircle.hide();
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.nav_change_team:
                startActivity(new Intent(NewMainActivity.this, SwitchTeamActivity.class));
                break;
            case R.id.nav_create_team:
                startActivity(new Intent(NewMainActivity.this, CreateTeamActivity.class));
                break;
            case R.id.nav_my_team:
                startActivity(new Intent(NewMainActivity.this, MyTeamActivity.class));
                break;
            case R.id.nav_serach:
                startActivity(new Intent(NewMainActivity.this, JoinCenterActivity.class));
                break;
        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);

        OkHttpClientUtils.cancelCall(UPDATE_USERINFO);
        OkHttpClientUtils.cancelCall(CHANGE_TODAY_FINISH_GOAL);
    }

    void initTabs() {
        int white = Color.parseColor("#ffffff");
        int black = Color.parseColor("#000000");

        al_act_circle.setBackgroundColor(white);
        al_person.setBackgroundColor(white);
        al_ranking.setBackgroundColor(white);

        iv_ranking.setImageResource(R.mipmap.tab_ranking_b);
        iv_person.setImageResource(R.mipmap.tab_person_b);
        iv_act_circle.setImageResource(R.mipmap.tab_ball_b);

        tv_act_circle.setTextColor(black);
        tv_person.setTextColor(black);
        tv_ranking.setTextColor(black);
    }

    void initFab() {
        FloatingActionButton fab = new FloatingActionButton(this);
        fab.setImageResource(R.drawable.fitness);
        CoordinatorLayout.LayoutParams layoutParams = new CoordinatorLayout.LayoutParams(CoordinatorLayout.LayoutParams.WRAP_CONTENT, CoordinatorLayout.LayoutParams.WRAP_CONTENT);
        int fab_margin = (int) getResources().getDimension(R.dimen.tabbar_height);
        layoutParams.setMargins(0, 0, fab_margin / 2, fab_margin + (fab_margin / 4));
        layoutParams.gravity = Gravity.BOTTOM | Gravity.END;
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.al_ranking:
                initTabs();
                hideAllFrag();
                al_ranking.setBackgroundColor(Color.parseColor("#06D5A6"));
                tv_ranking.setTextColor(Color.parseColor("#ffffff"));
                fragmentManager.beginTransaction().show(fragmentRanking).commit();
                iv_ranking.setImageResource(R.mipmap.tab_ranking_w);
                break;
            case R.id.al_act_circle:
                initTabs();
                hideAllFrag();
                al_act_circle.setBackgroundColor(Color.parseColor("#06D5A6"));
                tv_act_circle.setTextColor(Color.parseColor("#ffffff"));
                fragmentManager.beginTransaction().show(fragmentActivityCircle).commit();

                iv_act_circle.setImageResource(R.mipmap.tab_ball_w);
                break;
            case R.id.al_person:
                initTabs();
                hideAllFrag();
                al_person.setBackgroundColor(Color.parseColor("#06D5A6"));
                tv_person.setTextColor(Color.parseColor("#ffffff"));
                fragmentManager.beginTransaction().show(fragmentPerson).commit();

                iv_person.setImageResource(R.mipmap.tab_person_w);
                break;
        }
    }
}
